// 主页面，负责组合和 WebSocket 消息
import React, { useRef, useState, useEffect } from 'react';
import { View, SafeAreaView, StyleSheet, ScrollView, Text, TouchableOpacity } from 'react-native';
import { adapt, getBottomSafeHeight, adaptFontSize } from '../../ulits/Adapt';
import MessageList, { MessageType } from './MessageList';
import InputPanel from './InputPanel';
import io from 'socket.io-client';
import AsyncStorage from '@react-native-async-storage/async-storage';
// 请替换为你的服务器地址
const SOCKET_URL = 'http://192.168.46.222:3001';

// 假设有用户ID，实际项目应为真实登录用户ID
const MY_USER_ID = 'userB';
const OTHER_USER_ID = 'userA';

const Chat = () => {
  const [myUserName, setMyUserName] = useState('');
  // 消息列表 state
  const [messages, setMessages] = useState<MessageType[]>([]);
  // 用于滚动到最新消息
  const scrollViewRef = useRef<ScrollView>(null);
  // WebSocket 连接实例
  const socketRef = useRef<any>(null);

  useEffect(() => {
    AsyncStorage.getItem('login_username').then(name => {
      setMyUserName(name || '未登录用户');
    });
    
    // 连接 WebSocket
    const socket = io(SOCKET_URL, { 
      transports: ['websocket'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000
    });
    
    socketRef.current = socket;

    // 监听连接成功
    socket.on('connect', () => {
      console.log('WebSocket 连接成功');
      // 加入聊天房间
      socket.emit('join', { userId: MY_USER_ID });
    });

    // 监听连接错误
    socket.on('connect_error', (error) => {
      console.log('WebSocket 连接错误:', error);
    });

    // 监听收到消息
    socket.on('receiveMessage', (msg: any) => {
      console.log('收到消息:', msg);
      // 判断是对方发给自己的消息才处理
      if (msg.from === OTHER_USER_ID && msg.to === MY_USER_ID) {
        setMessages(prev => [...prev, msg]);
        setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100);
      }
    });

    return () => {
      if (socket) {
        socket.disconnect();
      }
    };
  }, []);

  // 发送消息
  const handleSend = (msg: MessageType) => {
    const chatMsg = { ...msg, from: MY_USER_ID, to: OTHER_USER_ID };
    setMessages([...messages, chatMsg]); // 本地也立即显示
    socketRef.current?.emit('sendMessage', chatMsg);
    setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 100);
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity>
          <Text style={styles.backButton}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.title}>{myUserName}</Text>
        <Text style={styles.dots}>···</Text>
      </View>
      {/* 消息内容区 */}
      <View style={styles.chatArea}>
        <MessageList messages={messages} scrollViewRef={scrollViewRef} />
      </View>
      {/* 输入区 */}
      <InputPanel onSend={handleSend} scrollViewRef={scrollViewRef} />
      {/* 底部安全距离 */}
      <View style={{ height: getBottomSafeHeight(), backgroundColor: '#111' }} />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: '#111' },
  header: {
    height: adapt(50),
    backgroundColor: '#111',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: adapt(12),
    justifyContent: 'space-between',
  },
  backButton: {
    fontSize: adaptFontSize(22),
    color: '#fff',
  },
  title: {
    fontSize: adaptFontSize(18),
    color: '#fff',
  },
  dots: {
    fontSize: adaptFontSize(22),
    color: '#fff',
  },
  chatArea: { flex: 1, backgroundColor: '#111' },
});

export default Chat;
